package com.zhida.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

import static com.zhida.common.utils.StaticKeyUtil.*;
@Slf4j
public class FileUtil {

    private static final String sourcePath = FILE_SERVER_DIR;

    public static void deleteDirectory(File directory) {
        if (directory.exists()) {
            File[] files = directory.listFiles();
            if (files != null) { //some JVMs return null for empty dirs
                for (File file : files) {
                    if (file.isDirectory()) {
                        //recursive call
                        deleteDirectory(file);
                    } else {
                        //direct delete
                        file.delete();
                    }
                }
            }
            //the directory is now empty so now it can be deleted
            directory.delete();
        }
    }
    public static void deleteFile(String fileDirectory,String fileName){
        Path directory = Paths.get(fileDirectory); // 替换为你的文件夹路径

        try {
            Files.walk(directory)
                    .filter(path -> path.toString().endsWith(fileName))
                    .findFirst()
                    .ifPresentOrElse(
                            fileToDelete -> {
                                try {
                                    Files.delete(fileToDelete);
                                    System.out.println("Deleted: " + fileToDelete);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            },
                            () -> System.out.println("No file found with name: " + fileName)
                    );
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static ArrayList<Map<String,String>> wsImageUpload(String to,
                                             List<MultipartFile> files,
                                             String from,
                                             String type) throws Exception {
        ArrayList<Map<String,String>> fileArr = new ArrayList<>();
        if(files == null || files.isEmpty()){ //若文件选择为空,就上传失败
            return null;
        }
        String filePath = ""; //指定到上传的文件路径
        int active = 1; // 群聊
        if("Group".equals(type)){  //群聊图片上传
            filePath = sourcePath + WS_GROUP_IMAGE_UPLOAD_DIR + to;
        }else if("User".equals(type)){  //2、私聊上传
            filePath = sourcePath + WS_USER_IMAGE_UPLOAD_DIR + from + "_" + to  ;
//            判断filepath是否存在
            active = 2; //私聊
        }
        File dir = new File(filePath);
        if (!dir.exists()) {
            if (active == 2){
                filePath = sourcePath + WS_USER_IMAGE_UPLOAD_DIR + to + "_" + from;
                dir = new File(filePath);
                if (!dir.exists()){
                    dir.mkdirs();
                }
            }else {
                //若路径不存在,则创建一个这样的文件夹
                dir.mkdirs();
            }
        }
        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();
            //            后缀
            String suf = fileName.substring(fileName.lastIndexOf(".")+1);
//            生成uuid作为文件名
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            fileName = uuid + "." + suf;
            try {
                File file1 = new File(filePath,fileName); //创建了一个File对象，名字是file1 ，路径是filePath，名字是fileName。
                file.transferTo(file1);    //将上传的文件写入创建好的文件中
                fileArr.add(Map.of("fileName",fileName,"filePath",filePath));  //上传成功后将文件名传回前端
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return fileArr;
    }

    public static boolean fileExist(String filePath){
        filePath = sourcePath + filePath;
        return new File(filePath).exists();
    }

    public static double getFileSize(String filePath){
        filePath = sourcePath + filePath;
        return (double) new File(filePath).length()/1024;
    }

    public static byte[] base642File(String base64String){
//        判断是png/jpg
        String imageType = "";
        if(base64String.contains("data:image/png;base64,")){
            imageType = "png";
            base64String = base64String.replace("data:image/png;base64,","").replace("\r\n","");
        }else {
            imageType = "jpg";
            base64String = base64String.replace("data:image/jpeg;base64,","").replace("\r\n","");
        }
        return Base64.getDecoder().decode(base64String);
    }

    public static String saveFile(byte[] fileBytes,String filePath,String fileSuf){
        String fileName = UUID.randomUUID().toString().replaceAll("-","") + fileSuf;
        try {
//            判断文件夹是否存在
            File dir = new File(filePath);
            if (!dir.exists()){
                dir.mkdirs();
            }
            Files.write(Paths.get(filePath,fileName), fileBytes);
            log.info("写入文件成功：文件路径：{}，文件名：{}",filePath,fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileName;
    }

    public static String getBase64FileSuf(String base64String){
        if(base64String.contains("data:image/png;base64,")){
            return ".png";
        }else {
            return ".jpeg";
        }
    }

}
